#include <iostream>
#include <string>
#include <thread_pool/XThreadPool.h>
#include "xrouter_server.h"
#include <XMsg.h>
#include "xservice_proxy.h"
#include <register_client/xregister_client.h>
#include <xplatform/XTools.h>
#include <xplatform/protobuf/xmsg_com.pb.h>
#include <config/config_client/XConfigClient.h>
using namespace std;
int main(int argc, char *argv[])
{
    //
    cout<<"xms_gateway API_GATEWAY_PORT REGISTER_IP REGISTER_PORT"<<endl;
    unsigned short server_port = API_GATEWAY_PORT;
    if(argc > 1){
        server_port = atoi(argv[1]);
    }
    cout << "server_port:" << server_port << endl;
    string register_ip = "127.0.0.1";
    if(argc > 2){
        register_ip = argv[2];
    }
    int register_port = REGISTER_PORT;
    if(argc > 3){
        register_port = atoi(argv[3]);
    }
    // 注册到注册中心
    XRegisterClient::Get()->MsgFuncCallback();
    XRegisterClient::Get()->setServerPort(register_port);
    XRegisterClient::Get()->setServerIP(register_ip.c_str());
    XRegisterClient::Get()->RegisterServer(API_GATEWAY_NAME,server_port,"127.0.0.1");
    // 等待注册中心连接
    XRegisterClient::Get()->waitConnected(3);
    XRegisterClient::Get()->GetServiceReq(nullptr);
    // 初始化服务代理（获取微服务列表）
    XServiceProxy::Get()->Init();
    // 自动重连
    XServiceProxy::Get()->Start();
    // 连接配置中心，获取配置
    // 如果有多个配置中心，只取第一个
    auto configs = XRegisterClient::Get()->GetService(CONFIG_NAME,10);
    cout << "configs.size():" << configs.services().size() << endl;
    if(configs.services().size()<=0){
        XCOM_LOG_DEBUG("configs.size() <= 0");
    }else{
        auto conf = configs.services(0);
        static xmsg::XGatewayConfig config;
        // 开启定时器，定时重新获取配置
        bool ret = XConfigClient::Get()->StartGetConfig(
            conf.ip().c_str(),// 配置中心ip
            conf.port(),// 配置中心端口
            nullptr,// 本地ip,nullptr表示取本地ip
            server_port,// 本地端口
            &config// 配置
        );
        if(ret){
            cout<<"连接配置中心成功"<<endl;
            bool ok = false;
            bool is_ssl = XConfigClient::Get()->GetBool("ssl",&ok);
        }
    }
    XRouterServer service;
    service.set_server_port_(server_port);
    service.set_thread_count_(3);
    service.Start();
    XThreadPool::Wait();
}